/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/*
 * The actual dialog window that handles logging in.
 */
/**/

package com.pentajock.docdb.dialogs;

import com.pentajock.docdb.Main;
import com.pentajock.docdb.database.DBController;
import com.pentajock.docdb.images.DBImages;
import com.pentajock.docdb.lang.Lang;
import com.pentajock.docdb.listeners.AutoTextSelectionFocusListener;
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.*;
/**
 *
 * @author tfino
 */


// NEEDS WORK FOR EXTENDING FRAME
public class LoginDialog extends JDialog {
		/*
		 * User Interface components.
		 */
		private JTextField userField;
		private JPasswordField passField;
		private JButton loginButton;
		private JButton cancelButton;
                
                /**/
                private static final String title = Lang.BUTTON.getText("LOGIN", "Login");
		
		private LoginFrame extendingFrame;
		private boolean dialogCanceled;
		private String CANCEL_DIALOG_INPUT_KEY = "CANCEL_DIALOG";
                
		public LoginDialog(LoginFrame extendingFrame) {
			super(extendingFrame, title, true);
			//Utils.setIconImage(this, DBImages.LOGIN_WINDOW.getImage());
			this.extendingFrame = extendingFrame;
                        constructorHelper();
		}
                
                public LoginDialog() {
                        super();
                        this.extendingFrame = null;
                        constructorHelper();
                }
                
                private void constructorHelper() {
                        dialogCanceled = false;
			
			initializeObjects();
			layoutFrame();
			addListeners();
			
			getRootPane().setDefaultButton(loginButton);
			setResizable(false);
			pack();
			setLocationRelativeTo(null);   
                }

		private void initializeObjects() {
			userField = new JTextField(10);
			passField = new JPasswordField(10);
			loginButton = new JButton(Lang.BUTTON.getText("LOGIN", "Login"), DBImages.APPLY_BUTTON.getIcon());
			loginButton.setDefaultCapable(true);
			cancelButton = new JButton(Lang.BUTTON.getText("CANCEL", "Cancel"), DBImages.EXIT_BUTTON.getIcon());
			
			loginButton.setMnemonic(Lang.BUTTON.getMnemonic("LOGIN", KeyEvent.VK_L));
			cancelButton.setMnemonic(Lang.BUTTON.getMnemonic("CANCEL", KeyEvent.VK_C));
		}
		
		private void layoutFrame() {
			int hAlign = SwingConstants.RIGHT;
			
			JLabel userLabel = new JLabel(Lang.MISC.getText("USER_NAME", "Username:"), DBImages.USER_ICON.getIcon(), hAlign);
			userLabel.setDisplayedMnemonic(Lang.MISC.getDisplayedMnemonic("USER_NAME", 'U'));
			userLabel.setLabelFor(userField);
			
			JLabel passLabel = new JLabel(Lang.MISC.getText("PASSWORD", "Password:"), DBImages.KEY_ICON.getIcon(), hAlign);
			passLabel.setDisplayedMnemonic(Lang.MISC.getDisplayedMnemonic("PASSWORD", 'P'));
			passLabel.setLabelFor(passField);
			
			JPanel loginPanel = new JPanel(new GridLayout(2, 2, 4, 4));
			loginPanel.add(userLabel);
			loginPanel.add(userField);
			loginPanel.add(passLabel);
			loginPanel.add(passField);
			loginPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
			
			JPanel buttonPanel = new JPanel(new FlowLayout());
			buttonPanel.add(loginButton);
			buttonPanel.add(cancelButton);
			
			getContentPane().add(loginPanel, BorderLayout.CENTER);
			getContentPane().add(buttonPanel, BorderLayout.SOUTH);
		}
		
		private void addListeners() {
			addWindowListener(new WindowAdapter() {
                            @Override
				public void windowClosing(WindowEvent e) {
					cancelDialog();
				}
			});
			
			addComponentListener(new ComponentAdapter() {
                            @Override	
                                public void componentShown(ComponentEvent e) {
					passField.requestFocusInWindow();
				}
				
                            @Override
				public void componentHidden(ComponentEvent e) {
					if (extendingFrame != null)
                                            extendingFrame.hideDummyWindow();
				}
			});
			
			loginButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if(isFirstLogin()) {
						JOptionPane.showMessageDialog(LoginDialog.this, "<html>This is your first time logging in.<br>Please set up your password now.", "First Login", JOptionPane.INFORMATION_MESSAGE);
						PasswordDialog passDialog = new PasswordDialog(LoginDialog.this, true, getUserName());
						passDialog.setVisible(true);
						if(passDialog.isSuccessful()) {
							setVisible(false);
						}
					}
					else if(checkPassword()) {
						setVisible(false);
					}
					else {
						JOptionPane.showMessageDialog(LoginDialog.this, "Incorrect username or password!", "Login Error", JOptionPane.ERROR_MESSAGE);
						passField.requestFocusInWindow();
					}
				}
			});
			
			cancelButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					cancelDialog();
				}
			});
			
			/*
			 * Mimic the usual textbox behavior of selecting the text
			 * when the textbox gains focus.
			 */
			userField.addFocusListener(new AutoTextSelectionFocusListener(userField));
			passField.addFocusListener(new AutoTextSelectionFocusListener(passField));
			/**/
			
			/*
			 * Map key strokes to actions.
			 */
			InputMap inputMap = new ComponentInputMap((JComponent)getContentPane());
			inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), CANCEL_DIALOG_INPUT_KEY);
			
			ActionMap actionMap = new ActionMap();
			actionMap.put(CANCEL_DIALOG_INPUT_KEY, new AbstractAction() {
				public void actionPerformed(ActionEvent e) {
					cancelDialog();
				}
			});
			
			((JComponent)getContentPane()).setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);
			((JComponent)getContentPane()).setActionMap(actionMap);
			/**/
		}
		
		private void cancelDialog() {
			dialogCanceled = true;
			setVisible(false);
		}
		
		public String getUserName() {
			String user = userField.getText();
			if(user == null) {
				user = "";
			}
			return user.trim();
		}
		
		public boolean isCanceled() {           
			return dialogCanceled;
		}
            
             @Override
		public void setVisible(boolean b) {
			if(b) {
				userField.setText(System.getProperty("user.name"));
				passField.setText("");
				setLocationRelativeTo(null);
			}
			super.setVisible(b);
		}
		
		private boolean isFirstLogin() {
			try {
				return DBController.isFirstLogin(getUserName());
			}
			catch(SQLException ex) {
				Main.printStackTrace(ex, "Error while checking for first login status.");
			}
			return false;
		}
		
		private boolean checkPassword() {
			// Hardcode a login?
			/* 
			if (getUserName().equals("dbclient") && new String(passField.getPassword()).equals("dbclient")) return true;
			*/
			try {
				return DBController.checkPassword(getUserName(), new String(passField.getPassword()));
			}
			catch(SQLException ex) {
				Main.printStackTrace(ex, "Database error");
			}
			return false;
		}
	}
